package com.fanrenqiji.common.factory;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年3月12日 上午10:21:58
 * @description
 */
public class JSONFactory extends ObjectMapper {

	private volatile static JSONFactory jsonFactory = null;

	public static JSONFactory getInstance() {
		if (jsonFactory == null) {
			synchronized (JSONFactory.class) {
				jsonFactory = new JSONFactory();
			}
		}
		return jsonFactory;
	}

	/**
	 * 获得将要转化的JSON集合 {3=[7, 6], 1=[10, 9]} TO
	 * [{"id":"3","featureValues":[{"id":"7"
	 * },{"id":"6"}]},{"id":"1","featureValues":[{"id":"10"},{"id":"9"}]}]
	 * 
	 * @param maps
	 * @return jsonString.
	 */
	public static List<Object> parseMapToList(Map<String, HashSet<String>> maps) {
		// 将数据解析成想要的数据
		Iterator<String> it = maps.keySet().iterator();
		List<Object> parentList = Lists.newArrayList();
		while (it.hasNext()) {
			String key = it.next();
			Map<String, Object> attr = Maps.newHashMap();
			attr.put("id", key);
			Iterator<String> childIt = maps.get(key).iterator();
			List<Map<String, String>> childList = Lists.newArrayList();
			while (childIt.hasNext()) {
				Map<String, String> attrValue = Maps.newHashMap();
				attrValue.put("id", childIt.next());
				childList.add(attrValue);
			}
			attr.put("featureValues", childList);
			parentList.add(attr);
		}
		return parentList;
	}

	/**
	 * parse String[]{"1-9", "1-10", "3-6", "3-7"} to {3=[7, 6], 1=[10, 9]}
	 * 
	 * @param attrs
	 * @return Map<String, HashSet<String>>
	 */
	public static Map<String, HashSet<String>> parseAttrArryToMap(
			String... attrs) {
		Map<String, HashSet<String>> first = Maps.newHashMap();
		for (String attr : attrs) {
			String[] a = attr.split("-");
			HashSet<String> set = first.get(a[0]);
			if (null == set) {
				set = new HashSet<String>();
			}
			set.add(a[1]);
			first.put(a[0], set);
		}
		return first;
	}

	/**
	 * //[1-9, 1-10, 3-6, 3-7] TO
	 * [{"id":1,"featureValues":[{"id":9},{"id":10}]},
	 * {"id":3,"featureValues":[{"id":6},{"id":7}]}]
	 * 
	 * @param attrs
	 * @return Map<String, HashSet<String>>
	 */
	public static List<Object> parseAttrArryToListMap(String... attrs) {
		return parseMapToList(parseAttrArryToMap(attrs));
	}

	public static void main(String[] args) {
		String[] s = new String[] { "1-9", "1-10", "3-6", "3-7" };
	}
}
